package a_doubleWrite;

/**
 * todo
 *
 * @author luolidong
 * @version 1.0
 * @create 2021-07-25 17:29
 */
public class L117_plus {
    public Node connect(Node root) {
        Node cur=root;//记录当前根节点
        while (cur!=null){
            //每层创建一个伪结点
            Node dummy=new Node();
            Node pre=dummy;
            while (cur!=null){
                //遍历cur的左右节点
                if(cur.left!=null){
                    pre.next=cur.left;
                    pre=pre.next;
                }
                if(cur.right!=null){
                    pre.next=cur.right;
                    pre=pre.next;
                }
                //cur变为它的next
                cur=cur.next;
            }
            //下一次的头结点即为前一个链表头
            cur=dummy.next;
        }
        return root;
    }
    private class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }
}
